package com.hk.common.utils;

import com.hk.common.constant.MsgException;

import java.beans.PropertyDescriptor;
import java.util.*;

/**
 * Bean操作类
 * @author zy
 * @date 2023-08-30
 */
public class BeanUtils {

    public static void copyProperties(Object toObject, Object fromObject) throws Exception {
        if (toObject == null) {
            throw new MsgException("copyProperties函数错误，toObject不可为空！");
        } else if (fromObject == null) {
            throw new MsgException("copyProperties函数错误，fromObject不可为空！");
        } else {
            Class<?> fromObjectClass = fromObject.getClass();
            Class<?> toObjectClass = toObject.getClass();
            if (toObjectClass.isAssignableFrom(fromObjectClass)) {
                org.springframework.beans.BeanUtils.copyProperties(fromObject, toObject);
            } else {
                org.apache.commons.beanutils.BeanUtils.copyProperties(toObject, fromObject);
            }

        }
    }

    public static <T> T copyAs(Object source, Class<T> destType) throws Exception {
        if (source == null) {
            return null;
        } else {
            T dest = destType.newInstance();
            copyProperties(dest, source);
            return dest;
        }
    }

    public static <T> List<T> copyAs(Collection<?> source, Class<T> destType) throws Exception {
        if (source == null) {
            return null;
        } else {
            List<T> result = new ArrayList<>();

            for (Object object : source) {
                result.add(copyAs(object, destType));
            }

            return result;
        }
    }

    private static String[] getIgnoreProperties(Object obj, List<String> copyPropertiesList) {
        String[] ignorePropertiesArr = null;
        PropertyDescriptor[] objPds = org.springframework.beans.BeanUtils.getPropertyDescriptors(obj.getClass());
        List<String> ignorePropertiesList = new ArrayList<>();
        PropertyDescriptor[] var5 = objPds;
        int var6 = objPds.length;

        for(int var7 = 0; var7 < var6; ++var7) {
            PropertyDescriptor objPd = var5[var7];
            if (objPd.getWriteMethod() != null && copyPropertiesList != null && !copyPropertiesList.isEmpty() && !copyPropertiesList.contains(objPd.getName())) {
                ignorePropertiesList.add(objPd.getName());
            }
        }

        if (!ignorePropertiesList.isEmpty()) {
            int size = ignorePropertiesList.size();
            ignorePropertiesArr = (String[])ignorePropertiesList.toArray(new String[size]);
        }

        return ignorePropertiesArr;
    }

    private static void copyPartProperties(Object source, Object target, List<String> copyPropertiesList) {
        String[] arr = getIgnoreProperties(target, copyPropertiesList);
        org.springframework.beans.BeanUtils.copyProperties(source, target, arr);
    }


}
